package zyy.wcx.datastructures.linkedlist;

/**
 * @program: data-structures-algorithms
 * @description: 单向链表的实现
 * @author: WuChengXing
 * @create: 2020-07-10 23:34
 **/
public class SingleLinkedListDemo {
    public static void main(String[] args) {
        SingleLinkedList singleLinkedList = new SingleLinkedList();
        singleLinkedList.addNode(new LinkedListNode(01, "node01"));
        singleLinkedList.addNode(new LinkedListNode(03, "node03"));
        singleLinkedList.addNode(new LinkedListNode(02, "node02"));
        singleLinkedList.addNode(new LinkedListNode(04, "node04"));
        singleLinkedList.listNode();
    }
}

/**
 * 单向链表类，管理节点
 */
class SingleLinkedList {
    /**
     * 定义头节点，只是用来辅助的
     */
    private LinkedListNode head = new LinkedListNode(0, "");

    /**
     * 添加节点
     */
    public void addNode(LinkedListNode node) {
        // 用头节点来辅助查询后面的节点
        LinkedListNode tempNode = head;
        while (true) {
            // 为空就跳出本次循环
            if (tempNode.next == null) {
                break;
            }
            // 继续往后遍历，直至找到下一个节点为空的节点（即尾结点）
            tempNode = tempNode.next;
        }
        // 将节点插入最后
        tempNode.next = node;
    }

    /**
     * 遍历节点
     */
    public void listNode() {
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        LinkedListNode temp = head.next;
        while (true) {
            if (temp == null) {
                break;
            }
            System.out.println(temp);
            temp = temp.next;
        }
    }
}

class LinkedListNode {
    /**
     * 节点编号
     */
    public Integer no;

    /**
     * 节点的名称
     */
    public String nodeName;

    /**
     * 下一个节点域
     */
    public LinkedListNode next;

    public LinkedListNode(Integer no, String nodeName) {
        this.no = no;
        this.nodeName = nodeName;
    }

    @Override
    public String toString() {
        return "LinkedListNode{" +
                "no=" + no +
                ", nodeName='" + nodeName + '\'' +
                '}';
    }
}


